<template>
  <div class="dashboard-container">
    <div class="dashboard-text">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>图书列表</span>
          <div class="input-with-div">
            <span>所有状态</span>
            <el-select slot="prepend" v-model="select1" class="mySelect1" placeholder="请选择" @change="change1($event)">
              <el-option label="无" value="null" />
              <el-option label="作者" value="book_author" />
              <el-option label="类别" value="book_type" />
              <el-option label="书名" value="book_name" />
              <el-option label="出版社" value="book_press" />
              <el-option label="状态" value="book_state" />
              <el-option label="库存" value="book_stock" />
            </el-select>
            <span>所有类别</span>
            <el-select slot="prepend" v-model="select2" class="mySelect2" placeholder="请选择" @change="change2">
              <el-option value="全部" />
              <el-option v-for="(book,index) in bookType" :key="index" :value="book" />
            </el-select>
            <!-- <el-button slot="append">筛选</el-button> -->
            <el-row class="demo-autocomplete">
              <el-col :span="12" class="inline-col">
                <el-autocomplete
                  v-model="state1"
                  class="inline-input"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入内容"
                  @select="handleSelect"
                  @input="inputChange"
                />
                <el-button @click.enter="searchBook">查找</el-button>
              </el-col>
              <el-button @click="showDialog">添加图书</el-button>
            </el-row>
          </div>

        </div>
        <div>
          <template>
            <el-table
              :data="bookData"
              border
              style="width: 100%"
            >
              <el-table-column
                fixed
                prop="book_id"
                label="编号"
                width="120"
              />
              <el-table-column
                prop="book_author"
                label="作者"
                width="140"
              />
              <el-table-column
                prop="book_type"
                label="类别"
                width="100"
              />
              <el-table-column
                prop="book_name"
                label="书名"
                width="240"
              />
              <el-table-column
                prop="book_press"
                label="出版社"
                width="300"
              />
              <el-table-column
                prop="book_state"
                label="状态"
                width="80"
              />
              <el-table-column
                prop="book_stock"
                label="库存"
                width="60"
              />
              <el-table-column
                fixed="right"
                label="操作"
                width="150"
              >
                <template slot-scope="scope">
                  <el-button type="warning" size="small" @click="modifyBook(scope.row)">修改</el-button>
                  <el-button size="small" type="danger" @click="deleteBook(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>
        <div class="block">
          <el-pagination
            :current-page="value"
            :page-sizes="[10,20,30,40]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <!-- 添加图书的弹框 -->
    <el-dialog title="添加图书" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form">
        <el-form-item label="作者" :label-width="formWidth" prop="author">
          <el-input v-model="form.author" />
        </el-form-item>
        <el-form-item label="类别" :label-width="formWidth" prop="bookType">
          <el-input v-model="form.bookType" />
        </el-form-item>
        <el-form-item label="书名" :label-width="formWidth" prop="bookName">
          <el-input v-model="form.bookName" />
        </el-form-item>
        <el-form-item label="出版社" :label-width="formWidth" prop="bookPress">
          <el-input v-model="form.bookPress" />
        </el-form-item>
        <el-form-item label="库存" :label-width="formWidth" prop="bookStock">
          <el-input v-model="form.bookStock" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancalAdd">取 消</el-button>
        <el-button type="primary" @click="addBook">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改图书的弹框 -->
    <el-dialog title="修改图书" :visible.sync="modifyBookInfo">
      <el-form ref="modifyForm" :model="modifyForm">
        <el-form-item label="作者" :label-width="formWidth" prop="author">
          <el-input v-model="modifyForm.book_author" />
        </el-form-item>
        <el-form-item label="类别" :label-width="formWidth" prop="bookType">
          <el-input v-model="modifyForm.book_type" />
        </el-form-item>
        <el-form-item label="书名" :label-width="formWidth" prop="bookName">
          <el-input v-model="modifyForm.book_name" />
        </el-form-item>
        <el-form-item label="出版社" :label-width="formWidth" prop="bookPress">
          <el-input v-model="modifyForm.book_press" />
        </el-form-item>
        <el-form-item label="状态" :label-width="formWidth" prop="bookState">
          <el-input v-model="modifyForm.book_state" />
        </el-form-item>
        <el-form-item label="库存" :label-width="formWidth" prop="bookStock">
          <el-input v-model="modifyForm.book_stock" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancalAdd">取 消</el-button>
        <el-button type="primary" @click="modifyBookHandler">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addBook, getBookinfo, mdBook, dlBook } from '@/api/book'
export default {
  name: 'BManage',
  data() {
    return {
      select1: '',
      select2: '全部',
      restaurants: [],
      state1: '',
      bookData: [],
      searchType: 'book_name',
      bookType: [],
      dialogFormVisible: false,
      form: {
        bookName: '',
        bookType: '',
        author: '',
        bookStock: '',
        bookState: '在馆',
        bookPress: ''

      },
      formWidth: '120px',
      total: 0,
      value: 1,
      offset: 10,
      modifyBookInfo: false,
      modifyForm: {
        book_name: '',
        book_type: '',
        book_author: '',
        book_stock: '',
        book_state: '在馆',
        book_press: '',
        book_id: 0,
        if_book_borrowUse: ''
      },
      AllBook: [],
      isFilter: false,
      bookFilterData: []
    }
  },
  computed: {
  },
  mounted() {
    this.getBook()
  },
  methods: {
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleSelect(item) {
      console.log(item)
    },
    async handleSizeChange(val) {
      this.offset = val
      const bookData = await getBookinfo(this.value, val)
      this.bookData = [...bookData.data]
    },
    async handleCurrentChange(val) {
      this.value = val
      if (this.isFilter) {
        this.filterBook()
      } else {
        this.renderBook(this.value, this.offset)
      }
    },
    change1(e) {
      if (e === 'null') {
        this.renderBook(this.value, this.offset)
      } else {
        this.searchType = e
      }
    },
    searchBook() {
      const that = this
      this.bookData = this.bookData.filter(item => item[that.searchType] === that.state1)
    },
    async inputChange() {
      if (this.state1 === '') {
        this.getBook()
      }
    },
    async change2() {
      const bookData = await getBookinfo()
      this.bookData = [...bookData.data]
      this.value = 1
      // this.renderBook(this.value, this.offset)
      if (this.select2 === '全部') {
        this.isFilter = false
        this.renderBook(this.value, this.offset)
        this.total = this.AllBook.length
        return
      } else {
        this.filterBook()
        this.total = this.bookFilterData.length
        this.isFilter = true
      }
    },
    showDialog() {
      this.dialogFormVisible = true
    },
    async addBook() {
      const result = await addBook(this.form)
      if (result.data) {
        this.$message.error('图书已经存在，无需再次添加')
      } else {
        this.$message({
          message: '添加图书成功',
          type: 'success'
        })
      }
      this.$refs.form.resetFields()
      this.dialogFormVisible = false
      this.handleCurrentChange(this.value)
    },
    cancalAdd() {
      this.modifyBookInfo = false
      this.dialogFormVisible = false
      this.$refs.form.resetFields()
      this.$refs.modifyForm.resetFields()
    },
    // 修改图书信息
    modifyBook(currentBookInfo) {
      this.modifyBookInfo = true
      // console.log(currentBookInfo)
      this.modifyForm = { ...currentBookInfo }
    },
    async modifyBookHandler() {
      // console.log(this.modifyForm)
      const res = await mdBook(this.modifyForm)
      console.log(res.status)
      if (res.status === 0) {
        this.$message({
          type: 'success',
          message: '修改图书成功!'
        })
        this.getBook()
      }
      this.modifyBookInfo = false
    },
    // 初始化图书信息
    async getBook() {
      const bookData = await getBookinfo(this.value, this.offset)
      const arr = []
      this.bookData = [...bookData.data]
      this.total = bookData.total
      this.AllBook = bookData.totalData
      this.bookData = [...bookData.data]
      bookData.totalData.forEach(item => {
        arr.push(item.book_type)
      })
      this.bookType = [...new Set(arr)]
    },
    // 删除图书
    deleteBook(bookinfo) {
      this.$confirm('确定要删除该图书, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.bookData.length <= 1 && this.value !== 1) {
          this.value -= 1
          this.getBook()
        }
        return dlBook(bookinfo)
      }).then(res => {
        if (res.status === 0) {
          this.$message({
            type: 'success',
            message: '删除图书成功!'
          })
          this.getBook()
        } else {
          this.$message.error('删除图书失败')
        }
      })
    },
    async renderBook(book1, book2) {
      const bookData = await getBookinfo(book1, book2)
      this.bookData = [...bookData.data]
    },
    filterBook() {
      this.bookFilterData = [...this.AllBook.filter(item => item.book_type === this.select2)]
      this.bookData = this.bookFilterData.filter((item, index) => {
        if ((1 + (this.value - 1) * this.offset) - 1 <= index && index < (this.value * this.offset) - 1) {
          return item
        }
      })
    }

  }

}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
 .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    // width: 480px;
    font-size: 24px;
  }
  .el-select .el-input {
    width: 130px;
  }
  .input-with-div{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    // width: 500px;
    font-size: 14px;
    span{
      margin: 0 10px;
    }
    .inline-col {
      display: flex;
      width: 300px;
      margin: 0 20px;
    }
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .mySelect1{
    width: 100px;
    text-align: center;
    padding: 0;
  }
   .mySelect2{
     margin:0px;
    width: 100px;
    text-align: center;
    padding: 0;
  }
  .inline-input{
    margin-right: 10px;
  }
  .block {
    margin-top: 30px;
  }
</style>
